import { FindOptions, MongoClient, ObjectId, UpdateFilter } from "mongodb";

const url = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    const db = client.db("hello");
    const res = await db.command({ ping: 1 }); // 测试数据库是否成功
    console.log("connected", res);
    // 数据的插入
    const userCollection = db.collection<{ hobbies: string[] }>("user");
    const result = await userCollection.findOne({
      // hobbies: ["golf", "music", "reading"],  // 全量匹配
      /* hobbies: {
        $all: ["golf", "music"]   // 模糊匹配
      } */
      // hobbies: "golf",
      hobbies: {
        $regex: /gol/g,
      },
    });
    const updateFilter: UpdateFilter<{ name: string; age: number; hobbies: string[] }> = {
      // 更新
      $set: {
        "hobbies.$": "golf11-new",
      },
    };
    const updateDoc = await userCollection.updateOne({ _id: new ObjectId("68ce7120858262e08cfed019"), hobbies: "golf" }, updateFilter);
    console.log(updateDoc);
  } catch (error) {
    console.error("error", error);
  } finally {
    await client.close();
  }
}

run();
